<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form>
        <el-form-item>
          <p style="float: left; font-family: Helvetica; font-size: 28px; margin: 8px auto;padding-left: 4px;">任务列表</p>
          <el-button type="primary" style="float: left;margin: 12px 8px;" size="small" icon="plus"
                     @click="convertTaskButton">
            创建城市管理检测任务
          </el-button>

          <div style="float: right; margin: 8px auto;padding-left: 4px;">
            <el-cascader size="small"
                         v-model="value"
                         :options="options"
                         @change="handleChange"></el-cascader>
          </div>
        </el-form-item>

      </el-form>
    </div>
    <!--任务列表-->
    <div>

      <el-table :data="taskList" v-loading.body="listLoading" element-loading-text="拼命加载中" border fit
                highlight-current-row>
        <el-table-column align="center" label="序号" width="70">
          <template slot-scope="scope">
            <span v-text="getIndex(scope.$index)"> </span>
          </template>
        </el-table-column>

        <el-table-column v-if="false" align="center" label="ID" prop="id" width="80"></el-table-column>

        <el-table-column align="center" label="任务名称" prop="taskName" style="width: 30px;"></el-table-column>

        <el-table-column align="center" label="任务类型" width="100">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.taskType==='1'" effect="plain">{{ taskTypeName.off_video }}</el-tag>
            <el-tag type="primary" v-if="scope.row.taskType==='2'" effect="plain">{{ taskTypeName.image }}</el-tag>
          </template>
        </el-table-column>


        <el-table-column align="center" label="检测源文件" style="width: 30px;">
          <template slot-scope="scope">
            <div v-for="taskFile in scope.row.taskFiles" align="center">
              <span align="center" style="display: inline-block;">{{
                  taskFile.fileName
                }}</span>
            </div>
          </template>
        </el-table-column>


        <el-table-column align="center" label="检测目标文件" style="width: 30px;">
          <template slot-scope="scope">
            <div v-for="convertedFile in scope.row.convertedFiles" align="center">
              <span align="center" style=" display: inline-block; ">{{
                  convertedFile.fileName
                }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column align="center" label="算法类型" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.algorithmType==='1'">{{ algorithmTypeList.detectFireExits }}</span>
            <span v-else-if="scope.row.algorithmType==='2'">{{ algorithmTypeList.detectFirePerson }}</span>
            <span v-else-if="scope.row.algorithmType==='3'">{{ algorithmTypeList.detectFireDehazing }}</span>
            <span v-else-if="scope.row.algorithmType==='4'">{{ algorithmTypeList.detectFire }}</span>
            <span v-else-if="scope.row.algorithmType==='5'">{{ algorithmTypeList.detectFireDoor }}</span>
          </template>

        </el-table-column>

        <!--任务状态  1.创建 2.成功 3.失败 4.取消-->
        <el-table-column align="center" label="任务状态" width="120">
          <template slot-scope="scope">
            <el-tag v-text="taskStatusName.create" v-if="scope.row.taskStatus==='1'"></el-tag>
            <el-tag type="success" v-text="taskStatusName.success" v-if="scope.row.taskStatus==='2'"></el-tag>
            <el-tag type="info" v-text="taskStatusName.partialSuccess" v-if="scope.row.taskStatus==='3'"></el-tag>
            <el-tag type="danger" v-text="taskStatusName.fail" v-if="scope.row.taskStatus==='4'"></el-tag>
            <el-tag type="warning" v-text="taskStatusName.cancel" v-if="scope.row.taskStatus==='5'"></el-tag>
            <el-tag type="danger" v-text="taskStatusName.giveTaskError" v-if="scope.row.taskStatus==='8'"></el-tag>
            <el-tag type="primary" v-text="taskStatusName.giveTaskSuccess" v-if="scope.row.taskStatus==='9'"></el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="创建时间" width="160">
          <template slot-scope="scope">
            <span v-text="dateToString(scope.row.createTime)"></span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="最近修改时间" width="160">
          <template slot-scope="scope">
            <span v-text="dateToString(scope.row.updateTime)"></span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="120">
          <template slot-scope="scope">
            <el-button size="small" style="padding: 4px 8px;" @click="getConvertResultNotify(scope.$index)">详情
            </el-button>
            <el-button size="small" style="padding: 4px 8px;" @click="deleteConvertTask(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页条   -->
    <div>
      <div style="width: 100%;height: auto;margin-top: 10px;">
        <div class="block" style="width: 45%;height: auto; margin: 0 0;">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="listQuery.pageNum"
            :page-sizes="listQuery.sizeList"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="listQuery.totalCount">
          </el-pagination>
        </div>
      </div>
    </div>


    <!-- 任务结果通知响应对话框 -->
    <el-dialog :fullscreen="true" :title="pageParams.title" :visible.sync="pageParams.dialogFormVisible"
               v-on:close="closeDialog(1)"
               style="min-width: 600px" width="50%">
      <el-form ref="params" :model="convertTaskNotifyResponse" rel="convertTaskNotifyResponse">

        <el-form-item v-if="false" label="任务ID:" style="width: 95%; margin-bottom: 0;">
          <span>{{ convertTaskNotifyResponse.id }}</span>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="任务名称:" style="width: 95%;margin-bottom: 0;">
              <span>{{ convertTaskNotifyResponse.taskName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="算法类型:" style="width: 95%;margin-bottom: 0;">
              <span v-if="convertTaskNotifyResponse.algorithmType==='1'">{{ algorithmTypeList.detectFireExits }}</span>
              <span
                v-else-if="convertTaskNotifyResponse.algorithmType==='2'">{{
                  algorithmTypeList.detectFirePerson
                }}</span>
              <span
                v-else-if="convertTaskNotifyResponse.algorithmType==='3'">{{
                  algorithmTypeList.detectFireDehazing
                }}</span>
              <span v-else-if="convertTaskNotifyResponse.algorithmType==='4'">{{ algorithmTypeList.detectFire }}</span>
              <span
                v-else-if="convertTaskNotifyResponse.algorithmType==='5'">{{ algorithmTypeList.detectFireDoor }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务类型:" style="width: 95%;margin-bottom: 0;">
              <template>
                <el-tag v-if="convertTaskNotifyResponse.taskType==='1' || convertTaskNotifyResponse.taskType==='video'"
                        effect="plain" type="success">
                  {{
                    taskTypeName.off_video
                  }}
                </el-tag>

                <el-tag v-if="convertTaskNotifyResponse.taskType==='2' || convertTaskNotifyResponse.taskType==='image'"
                        effect="plain" type="primary">
                  {{
                    taskTypeName.image
                  }}
                </el-tag>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--   1:任务创建, 2:转换成功, 3:转换部分成功, 4:转换失败, 5:取消转换,  8:下发失败, 9:下发成功     -->
            <!--              success       info          danger     warning      danger   primary-->
            <el-form-item label="任务状态:" style="width: 95%;margin-bottom: 0;">
              <template>
                <el-tag v-text="taskStatusName.create" v-if="convertTaskNotifyResponse.taskStatus==='1'"></el-tag>
                <el-tag type="success" v-text="taskStatusName.success"
                        v-if="convertTaskNotifyResponse.taskStatus==='2'"></el-tag>
                <el-tag type="info" v-text="taskStatusName.partialSuccess"
                        v-if="convertTaskNotifyResponse.taskStatus==='3'"></el-tag>
                <el-tag type="danger" v-text="taskStatusName.fail"
                        v-if="convertTaskNotifyResponse.taskStatus==='4'"></el-tag>
                <el-tag type="warning" v-text="taskStatusName.cancel"
                        v-if="convertTaskNotifyResponse.taskStatus==='5'"></el-tag>
                <el-tag type="danger" v-text="taskStatusName.giveTaskError"
                        v-if="convertTaskNotifyResponse.taskStatus==='8'"></el-tag>
                <el-tag type="primary" v-text="taskStatusName.giveTaskSuccess"
                        v-if="convertTaskNotifyResponse.taskStatus==='9'"></el-tag>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="创建时间:" style="width: 95%;margin-bottom: 0;">
              <span v-text="dateToString(convertTaskNotifyResponse.createTime)"></span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最近修改时间:" style="width: 95%;margin-bottom: 0;">
              <span>{{ dateToString(convertTaskNotifyResponse.updateTime) }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="源文件名:" style="width: 95%;margin-bottom: 0;">
              <el-select v-model="selectOption.selectResourceFileName"
                         v-on:change="resourceChange($event, convertTaskNotifyResponse)" size="small"
                         placeholder="选择源文件">
                <el-option v-for="taskFile in convertTaskNotifyResponse.taskFiles" :key="taskFile.fileName"
                           :label="taskFile.fileName" :value="taskFile.fileName"></el-option>
              </el-select>
            </el-form-item>

            <el-card class="box-card" style="padding: 0;">
              <div v-if="resourceShowSwitch.show">
                <img :src="resourceImageOptions.imageUrl" style="width: 100%; height: auto;"/>
              </div>
              <div v-else class="player-container">
                <video ref="videoPlayer" v-model="resourcePlayerOptions.videoUrl" width="100%" height="auto"
                       :src="resourcePlayerOptions.videoUrl" controls>
                  <source :src="resourcePlayerOptions.videoUrl" style="width:100%; height:auto">
                </video>
                <!--                <video-player ref="videoPlayer" class="vjs-custom-skin" :options="resourcePlayerOptions"></video-player>-->
              </div>
            </el-card>
          </el-col>

          <el-col :span="12">
            <el-form-item label="目标文件名:" style="width: 95%;margin-bottom: 0;">
              <el-select v-model="selectOption.selectTaskFileName"
                         v-on:change="taskFileChange($event, convertTaskNotifyResponse)" size="small"
                         placeholder="选择目标文件">
                <el-option v-for="convertedFile in convertTaskNotifyResponse.convertedFiles"
                           :key="convertedFile.fileName" :label="convertedFile.fileName"
                           :value="convertedFile.fileName"></el-option>
              </el-select>
              <a v-if="selectOption.selectTaskFileName !== '' " :href="getDownloadHref(selectOption.selectTaskFileName)"
                 :download="selectOption.selectTaskFileName">
                <el-button size="small">下载</el-button>
              </a>
            </el-form-item>

            <el-card class="box-card" style="padding: 0;">
              <div v-if="taskFileShowSwitch.isDrawPolygon" style="width: 100%; height: auto;">
                <div v-if="taskFileShowSwitch.show" style="position: relative;" class="collapseDiv">
                  <div style="position: absolute; float: left; width: 100%; height: auto;" class="collapseDiv">
                    <img class="monitorDiv" :src="taskFileImageOptions.imageUrl" style="width: 100%; height: auto;"
                         id="targetImageDiv"/>
                  </div>
                  <canvas style="position: absolute; float: left" id="targetImageCanvas"></canvas>
                </div>

                <div v-else class="collapseDiv">
                  <div style="position: relative;" class="collapseDiv">
                    <video class="monitorDiv" ref="videoPlayer" id="targetVideoDiv"
                           v-model="taskFilePlayerOptions.videoUrl"
                           style="position: absolute; float: left; width: 100%; height: auto;"
                           :src="taskFilePlayerOptions.videoUrl" controls>
                      <source :src="taskFilePlayerOptions.videoUrl" style="width:100%; height:auto">
                    </video>
                    <canvas style="position: absolute; float: left" id="targetVideoCanvas"></canvas>
                  </div>
                </div>
              </div>
              <div v-else style="width: 100%; height: auto;">
                <div v-if="taskFileShowSwitch.show" style="width: 100%; height: auto;">
                  <img :src="taskFileImageOptions.imageUrl" style="width: 100%; height: auto;"/>
                </div>

                <div v-else>
                  <div style="width: 100%; height: auto;">
                    <video v-model="taskFilePlayerOptions.videoUrl" style="width: 100%; height: auto;"
                           :src="taskFilePlayerOptions.videoUrl" controls>
                      <source :src="taskFilePlayerOptions.videoUrl" style="width:100%; height:auto">
                    </video>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" title="Esc退出全屏" @click="pageParams.dialogFormVisible = false">取消
        </el-button>
      </div>
    </el-dialog>


    <!--  创建转换任务对话框  -->
    <!--  向服务器提交的数据保存在taskRequestData中，通过this.api()提交  -->
    <el-dialog :title="popoverPageParams.createTaskDialogTitle"
               :visible.sync="popoverPageParams.createTaskDialogFormVisible"
               width="50%">
      <el-form ref="taskRequestData" :model="taskRequestData" :rules="taskRequestDataRules"
               v-loading.body="popoverPageParams.createTaskDialogLoading"
               label-width="80px">

        <el-form-item label="任务名称" style="width: 95%" prop="taskName">
          <el-input v-model="taskRequestData.taskName" autoComplete="on"
                    v-on:blur="numberAndLetter(taskRequestData.taskName)" placeholder="输入名称"></el-input>
        </el-form-item>

        <!-- 1:检测道路， 2: 检测摊贩, 3:检测自行车     -->
        <el-form-item label="算法类型" style="width: 95%" prop="algorithmType" required>
          <el-select v-model="taskRequestData.algorithmType" autoComplete="on" placeholder="请选择算法类型">
            <el-option :label="algorithmTypeList.detectFireExits" value="1"></el-option>
            <el-option :label="algorithmTypeList.detectFirePerson" value="2"></el-option>
            <el-option :label="algorithmTypeList.detectFireDehazing" value="3"></el-option>
            <el-option :label="algorithmTypeList.detectFire" value="4"></el-option>
            <el-option :label="algorithmTypeList.detectFireDoor" value="5"></el-option>
          </el-select>
          <!--          <el-input v-model="taskRequestData.algorithmType" placeholder="输入算法类型"></el-input>-->
        </el-form-item>

        <el-form-item label="任务类型" prop="taskType" required>
          <el-select v-model="taskRequestData.taskType" autoComplete="on" placeholder="请选择任务类型">
            <el-option :label="taskTypeName.off_video" value="1"></el-option>
            <el-option :label="taskTypeName.image" value="2"></el-option>
          </el-select>
        </el-form-item>


<!--        <el-form-item label="缓存个数" style="width: 34.3%" prop="cacheNumber"-->
<!--                      v-if="(taskRequestData.algorithmType === 5 || taskRequestData.algorithmType === '5')">-->
<!--          <el-input v-model="taskRequestData.cacheNumber" autoComplete="on"-->
<!--                    v-on:blur="isNumber(taskRequestData.cacheNumber)" placeholder="输入单车检测缓存数,默认缓存10个"></el-input>-->
<!--        </el-form-item>-->

        <el-form-item label="文件名称" required>
          <!-- 选择文件列表弹框 -->
          <el-popover title="文件列表" placement="right" width="800" style="height: 550px;" trigger="click">
            <div style="float: right;  margin: 8px auto;padding-left: 4px;">
              <el-input clearable v-model="searchText" prefix-icon="el-icon-search" v-on:clear="searchEvent"
                        onkeypress='if(window.event.keyCode==13) this.blur()' v-on:blur="searchEvent" size="small"
                        style="width:200px; height: 40px; margin-top: 8px;" placeholder="请输入内容"/>
            </div>
            <el-table :data="popoverFileList" v-loading.body="popoverListLoading" element-loading-text="拼命加载中" border
                      fit @selection-change="handleSelectionChange" :row-key="getRowKeys"
                      highlight-current-row style="max-width: 800px;" height="550">
              <el-table-column align="center" :reserve-selection="true" @selection-change=""
                               type="selection"
                               width="40" label="文件选择">
              </el-table-column>
              <el-table-column align="center" label="序号" width="80">
                <template slot-scope="scope">
                  <span v-text="getPopoverIndex(scope.$index)"> </span>
                </template>
              </el-table-column>
              <el-table-column v-if="false" align="center" label="ID" prop="id" style="width: 40px;"></el-table-column>
              <el-table-column align="center" label="文件名称" prop="fileName" style="width: 40px;"></el-table-column>
              <el-table-column align="center" label="文件类型" width="120">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.fileType==='1' || scope.row.fileType===1 || scope.row.fileType==='video'"
                          size="small" type="success">{{
                      fileType.off_video
                    }}
                  </el-tag>
                  <el-tag v-if="scope.row.fileType==='2' || scope.row.fileType===2 || scope.row.fileType==='image'"
                          size="small" type="primary">{{
                      fileType.image
                    }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column align="center" label="创建时间" width="200">
                <template slot-scope="scope">
                  <span v-text="dateToString(scope.row.createTime)"></span>
                </template>
              </el-table-column>

            </el-table>

            <div v-if="paginationVisible" style="width: 100%;height: auto;margin-top: 10px;">
              <div class="block" style="width: 45%;height: auto; margin: 0 0;">
                <el-pagination
                  @size-change="handlePopoverSizeChange"
                  @current-change="handlePopoverCurrentChange"
                  :current-page="popoverListQuery.pageNum"
                  :page-sizes="popoverListQuery.sizeList"
                  :page-size="10"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="popoverListQuery.totalCount">
                </el-pagination>
              </div>
            </div>

            <el-button type="small" slot="reference" v-on:click="selectFile">
              <el-badge :value="selectNumber" :max="100" type="primary">
                选择文件
              </el-badge>
            </el-button>

          </el-popover>
          <div>
            <span v-for="taskFile in taskRequestData.taskFiles">
              <div onMouseOver="this.style.color='red'" onMouseOut="this.style.color='#000000'"
                   style="overflow-x:auto; white-space:nowrap; cursor: pointer;  float: left;margin-right: 6px; width: 30%;"
                   v-on:click="taskFileShow(taskRequestData.taskFiles,taskFile.fileId, taskFile.fileName)">
                {{ taskFile.fileName }}
              </div>
            </span>

          </div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="createConvertTask">立即创建</el-button>
        <el-button size="small" type="primary" @click="clearSelectFiles">清空所选文件</el-button>
        <el-button size="small" @click="popoverPageParams.createTaskDialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>


    <el-dialog id="imageAndVideoDialog" :title="showSwitch.title" :visible.sync="dialogVisible" width="50%"
               v-on:close="closeDialog(2)">
      <div v-if="showSwitch.show" style="width: 100%; height: auto;">
        <div v-if="showSwitch.isDrawPolygon" style="position: relative; width: 100%;" class="collapseDiv image">
          <div style="position: absolute; float: left; width: 100%;" class="collapseDiv">
            <img class="monitorDiv" style="width: 100%; height: auto;" :src="dialogImageUrl" alt=""
                 id="drawPolygonImage">
          </div>
          <canvas ref="image" style="position: absolute; float: left;" id="imageCanvas" class="testDiv"></canvas>
        </div>
        <div v-else style="width: 100%; height: auto;">
          <img :src="dialogImageUrl" style="width: 100%; height: auto;"/>
        </div>
      </div>

      <div v-else style="width: 100%; height: auto;">
        <div v-if="showSwitch.isDrawPolygon" style="position: relative; width: 100%;" class="collapseDiv video">
          <div class="collapseDiv" style="position: absolute; float: left; width: 100%;">
            <video class="monitorDiv" ref="videoPlayer" :autoplay="true" style="width: 100%;height: auto;"
                   v-model="dialogVideoUrl" :src="dialogVideoUrl" id="drawPolygonVideo" controls>
              <source :src="dialogVideoUrl" style="width:100%; height: auto;">
            </video>
          </div>
          <canvas ref="video" style="position: absolute; float: left;" id="videoCanvas" class="testDiv"></canvas>
        </div>
        <div v-else style="width: 100%; height: auto;">
          <video ref="videoPlayer" v-model="dialogVideoUrl" width="100%" height="auto" :src="dialogVideoUrl" controls>
            <source :src="dialogVideoUrl" style="width:100%; height:auto">
          </video>
        </div>
      </div>


      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary"
                   v-if="showSwitch.isCreateTask && (taskRequestData.algorithmType === 5 || taskRequestData.algorithmType === '5' || taskRequestData.algorithmType === 1 || taskRequestData.algorithmType === '1')"
                   @click="drawPolygonEvent(showSwitch.selectingFileName, true)">绘制待检测区域
        </el-button>
        <el-button size="small" type="primary"
                   v-if="showSwitch.isCreateTask && (taskRequestData.algorithmType === 5 || taskRequestData.algorithmType === '5' || taskRequestData.algorithmType === 1 || taskRequestData.algorithmType === '1')"
                   @click="drawPolygonEvent(showSwitch.selectingFileName, false)">绘制非检测区域
        </el-button>
        <el-button size="small" @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>


    <div class="monitorDiv" style="width: 200px; height: 100px"></div>

  </div>

</template>


<script>

let elementResizeDetectorMaker = require("element-resize-detector")
import "video.js"
import 'video.js/dist/video-js.css'
import 'vue-video-player/src/custom-theme.css'

import {parseTime} from '../../utils';
import axios from "axios";

const api = axios.create({
  baseURL: process.env.BASE_URL, // api的base_url
  timeout: 15000                  // 请求超时时间2
})

export default {
  name: "task",
  inject: ['reload'],
  data() {
    return {
      searchText: "",
      isSearch: false,
      isPreSearch: false,

      paginationVisible: true,

      dialogStyle: {
        width: 0,
        height: 0
      },
      getRowKeys(popoverFileList) {
        return popoverFileList.id
      },
      value: [0, 0],
      options: [{
        value: 0,
        label: '全部检测',
        children: [{
          value: 0,
          label: "全部类型"
        }, {
          value: 1,
          label: "离线视频"
        }, {
          value: 2,
          label: "图片"
        }]
      }, {
        value: 1,
        label: '消防通道检测',
        children: [{
          value: 0,
          label: "全部类型"
        }, {
          value: 1,
          label: "离线视频"
        }, {
          value: 2,
          label: "图片"
        }]
      }, {
        value: 2,
        label: '被困人员检测',
        children: [{
          value: 0,
          label: "全部类型"
        }, {
          value: 1,
          label: "离线视频"
        }, {
          value: 2,
          label: "图片"
        }]
      }, {
        value: 3,
        label: '火场图像去雾',
        children: [{
          value: 0,
          label: "全部类型"
        }, {
          value: 1,
          label: "离线视频"
        }, {
          value: 2,
          label: "图片"
        }]
      }, {
        value: 4,
        label: '火灾智能检测',
        children: [{
          value: 0,
          label: "全部类型"
        }, {
          value: 1,
          label: "离线视频"
        }, {
          value: 2,
          label: "图片"
        }]
      }, {
        value: 5,
        label: '防火门检测',
        children: [{
          value: 0,
          label: "全部类型"
        }, {
          value: 1,
          label: "离线视频"
        }, {
          value: 2,
          label: "图片"
        }]
      }],
      dialogImageUrl: "",
      dialogVideoUrl: "",

      selectNumber: "",

      //详情
      convertTaskResultNotify: {
        id: 0,//Integer
        taskStatus: 0,//Integer
        convertedFiles: [//Array
          {
            fileId: "",//String
            fileName: ""//String
          }
        ]
      },
      //弹出框的文件列表
      popoverFileList: [],
      //页面参数
      pageParams: {
        dialogFormVisible: false,
        title: '检测任务结果'
      },
      fileType: {
        off_video: "离线视频",
        image: "图片"
      },
      //弹出框分页条参数
      //页面参数
      popoverPageParams: {
        createTaskDialogTitle: "创建城市管理检测任务",
        createTaskDialogFormVisible: false,
        dialogFormVisible: false,
        title: '检测任务结果'
      },

      //创建任务请求上传参数
      taskRequestData: {
        algorithmType: '',//非必须String
        taskName: '',//非必须String
        taskType: '',//1:离线视频 2:图片String
        taskFiles: [],//String
        coordPoints: [],
        skipCoordPoints: [],
        cacheNumber: 10
      },
      taskRequestDataRules: {
        taskName: [{required: true, trigger: 'blur', message: "请输入任务名称，限字母或数字"}],
        algorithmType: [{required: true, trigger: 'blur', message: "请选择算法类型"}],
        taskType: [{required: true, trigger: 'blur', message: "请选择任务类型"}],
        taskFiles: [{required: true, trigger: 'blur', message: "请选择文件"}],
        cacheNumber: [{required: true, trigger: 'blur', message: "请输入单车检测缓存个数，仅限数字"}]
      },
      taskFileNames: [],
      //创建任务请求响应
      taskResponseResult: {
        code: '',
        msg: '',
        id: '',//任务ID
        info: ''//任务调度返回信息
      },

      //存放要显示的task数据,这是一个集合
      taskList: [],
      coordPoints: [],
      skipCoordPoints: [],


      //这不是一个集合
      convertTaskNotifyResponse: {},

      listLoading: true,
      popoverListLoading: false,

      //分页查询设置参数
      listQuery: {
        url: "/converttask/list",
        pageRow: 10,//页大小
        pageNum: 1,//当前页
        totalPage: 0,//总页数
        totalCount: 0,//总数据大小
        sizeList: [10, 20, 50, 100, 200]
      },

      listSearchQuery: {
        url: "/uploadfile/query"
      },

      //分页查询设置参数
      popoverListQuery: {
        url: "/uploadfile/list",
        pageRow: 10,//页大小
        pageNum: 1,//当前页
        totalPage: 0,//总页数
        totalCount: 0,//总数据大小
        sizeList: [10, 20, 50, 100]
      },
      //保存任务类型名称，便于显示
      taskTypeName: {
        image: '图片',
        off_video: '离线视频',
        on_video: '实时视频'
      },
      //<!--任务状态  1.创建 2.成功 3.失败 4.取消-->
      //1:任务创建, 2:转换成功, 3:转换部分成功, 4:转换失败, 5:取消转换,  8:下发失败, 9:下发成功
      //保存任务状态名称便于显示
      taskStatusName: {
        create: '任务创建',
        success: "检测成功",
        partialSuccess: "部分检测成功",
        fail: '检测失败',
        cancel: '取消检测',
        giveTaskError: "下发失败",
        giveTaskSuccess: "下发成功"
      },

      /////////////////////////////////////////
      //算法类型信息
      // 1、消防通道检测: detectFireExits
      // 2、被困人员检测: detectFirePerson
      // 3、火场图像去雾: detectFireDehazing
      // 4、火灾智能检测: detectFire
      // 5、防火门检测: detectFireDoor
      /////////////////////////////////////////
      algorithmTypeList: {
        detectFireExits: "消防通道检测",
        detectFirePerson: "被困人员检测",
        detectFireDehazing: "火场图像去雾",
        detectFire: "火灾智能检测",
        detectFireDoor: "防火门检测"
      },

      /////////////////////////////////
      //文件下载URL
      /////////////////////////////////
      fileDownloadUrl: "/repository",

      ////////////////////////////////////////////////////////
      //图片视频浏览窗口
      ////////////////////////////////////////////////////////
      //show开关，控制是否显示图片或则视频:true为图片， false为视频
      dialogVisible: false,
      showSwitch: {
        url: "/repository",
        title: "图片/视频",
        show: true,
        isCreateTask: false,
        isDrawPolygon: false,
        selectingFileName: ""
      },

      //视频显示
      resourcePlayerOptions: {
        videoUrl: ""
      },
      taskFilePlayerOptions: {
        videoUrl: ""
      },
      //图片显示
      resourceImageOptions: {
        imageUrl: "./placeholder.png"
      },
      taskFileImageOptions: {
        imageUrl: "./placeholder.png"
      },
      //show开关，控制是否显示图片或则视频
      resourceShowSwitch: {
        url: "/repository",
        dialogVisible: false,
        title: "图片/视频",
        show: true
      },
      taskFileShowSwitch: {
        url: "/repository",
        dialogVisible: false,
        title: "图片/视频",
        show: true,
        isDrawPolygon: false
      },
      //选择文件下拉框
      selectOption: {
        selectTaskFileName: "",
        selectResourceFileName: ""
      },
      polygonPoint: [],
      polygonNoCheckPoint: [],
      polygonId: 0
    }
  },
  mounted() {

  },
  watch: {
    dialogVisible: {
      handler(newName, oldName) {
        if (newName === false) {
          document.onmousedown = null
          let canvas = document.getElementById('imageCanvas')
          if (undefined !== canvas && canvas != null) {
            canvas.style.opacity = '0.7'
          }
        }
      },
      immediate: false
    },
    polygonPoint: {
      handler(newName, oldName) {
        let index = 0
        for (index; index < this.polygonPoint.length; index++) {
          if (this.polygonPoint[index].fileId === this.polygonId) {
            break
          }
        }
        if (this.showSwitch.show) {
          this.drawImageAndPoints("imageCanvas", "drawPolygonImage", this.polygonPoint[index].point, this.polygonNoCheckPoint[index].point)
        } else {
          this.drawImageAndPoints("videoCanvas", 'drawPolygonVideo', this.polygonPoint[index].point, this.polygonNoCheckPoint[index].point)
        }
      },
      deep: true,
      immediate: false
    },
    polygonNoCheckPoint: {
      handler(newName, oldName) {
        let index = 0
        for (index; index < this.polygonNoCheckPoint.length; index++) {
          if (this.polygonNoCheckPoint[index].fileId === this.polygonId) {
            break
          }
        }
        if (this.showSwitch.show) {
          this.drawImageAndPoints("imageCanvas", "drawPolygonImage", this.polygonPoint[index].point, this.polygonNoCheckPoint[index].point)
        } else {
          this.drawImageAndPoints("videoCanvas", 'drawPolygonVideo', this.polygonPoint[index].point, this.polygonNoCheckPoint[index].point)
        }
      },
      deep: true,
      immediate: false
    }
  },
  created() {

    //加载初期获得数据
    this.getTaskList(this.listQuery.url, this.listQuery.pageNum, this.listQuery.pageRow)
  },
  methods: {
    searchEvent() {
      if (this.searchText !== "") {
        this.conditionQuery(this.listSearchQuery.url, this.searchText)
        this.paginationVisible = false
      } else {
        this.getFileList(this.popoverListQuery.url, this.popoverListQuery.pageNum, this.popoverListQuery.pageRow)
        this.paginationVisible = true
      }
    },
    conditionQuery(url, fileName) {
      api({
        url: url + '/?fileName=' + fileName,
        method: "get"
      }).then(data => {
        data = data.data
        if (data.code === '100' || data.code === 100) {
          this.popoverFileList = data.info;
        } else {
          this.$message.error(data.msg)
        }
      }).catch(data => {
        this.$message.error('加载文件列表失败');
      })
    },
    algorithmSearch(algorithmType, fileType, fileList) {
      let tempFileList = []

      if (algorithmType !== 0 && fileType !== 0) {
        for (let index = 0; index < fileList.length; index++) {
          if (fileList[index].algorithmType === algorithmType.toString() && fileList[index].taskType === fileType.toString()) {
            tempFileList.push(fileList[index])
          }
        }
      } else if (algorithmType !== 0) {
        for (let index = 0; index < fileList.length; index++) {
          if (fileList[index].algorithmType === algorithmType.toString()) {
            tempFileList.push(fileList[index])
          }
        }
      } else if (fileType !== 0) {
        for (let index = 0; index < fileList.length; index++) {
          if (fileList[index].taskType === fileType.toString()) {
            tempFileList.push(fileList[index])
          }
        }
      } else {
        tempFileList = fileList
      }
      return tempFileList
    },
    handleChange(value) {
      this.getTaskList(this.listQuery.url, this.listQuery.pageNum, this.listQuery.pageRow)
    },
    //Date转string类型，显示时间
    dateToString(date) {
      if (date == null) {
        return "NAN"
      } else {
        return parseTime(date)
      }
    },

    //获得鼠标点击
    onmouseDownCheck(ev) {
      let mousePos = this.mouseCoords(ev);
      //鼠标点击的点
      let mousePosX = mousePos.x
      let mousePosY = mousePos.y
      this.$nextTick(() => {
        let image = null
        let imageDialog = null
        if (this.showSwitch.show) {
          image = document.getElementsByClassName("image")[0]
        } else {
          image = document.getElementsByClassName("video")[0]
        }
        imageDialog = document.getElementById("imageAndVideoDialog")

        let width = image.clientWidth
        let height = image.clientHeight
        let x_off = image.offsetLeft
        let y_off = image.offsetTop
        let offsetParent = image.offsetParent
        let offsetParentx_off = offsetParent.offsetLeft
        let offsetParenty_off = offsetParent.offsetTop


        let scrollTop = imageDialog.scrollTop
        let scrollLeft = imageDialog.scrollLeft
        //左上的坐标点
        let pos_x1 = offsetParentx_off + x_off - scrollLeft
        let pos_y1 = offsetParenty_off + y_off - scrollTop
        //右下点坐标
        let pos_x2 = pos_x1 + width
        let pos_y2 = pos_y1 + height
        if (mousePosX >= pos_x1 && mousePosX <= pos_x2) {
          if (mousePosY >= pos_y1 && mousePosY <= pos_y2) {
            // console.log("==================================")
            // console.log("左上点："+pos_x1 + "-" + pos_y1)
            // console.log("图片宽高："+width + "-" + height)
            // console.log("右下点："+pos_x2 + "-" + pos_y2)
            // console.log("鼠标点击点："+mousePosX+"-"+mousePosY)
            // console.log("鼠标点击坐标："+(mousePosX - pos_x1)+"-"+(mousePosY - pos_y1))

            for (let i = 0; i < this.polygonPoint.length; i++) {
              if (this.polygonPoint[i].fileId === this.polygonId) {
                let p = [(mousePosX - pos_x1) / width, (mousePosY - pos_y1) / height]
                this.polygonPoint[i].point.push(p)
              }
            }
          }
        }
      })
    },
    //获得鼠标点击
    onmouseDownNoCheck(ev) {
      let mousePos = this.mouseCoords(ev);
      //鼠标点击的点
      let mousePosX = mousePos.x
      let mousePosY = mousePos.y
      this.$nextTick(() => {
        let image = null
        let imageDialog = null
        if (this.showSwitch.show) {
          image = document.getElementsByClassName("image")[0]
        } else {
          image = document.getElementsByClassName("video")[0]
        }
        imageDialog = document.getElementById("imageAndVideoDialog")

        let width = image.clientWidth
        let height = image.clientHeight
        let x_off = image.offsetLeft
        let y_off = image.offsetTop
        let offsetParent = image.offsetParent
        let offsetParentx_off = offsetParent.offsetLeft
        let offsetParenty_off = offsetParent.offsetTop


        let scrollTop = imageDialog.scrollTop
        let scrollLeft = imageDialog.scrollLeft
        //左上的坐标点
        let pos_x1 = offsetParentx_off + x_off - scrollLeft
        let pos_y1 = offsetParenty_off + y_off - scrollTop
        //右下点坐标
        let pos_x2 = pos_x1 + width
        let pos_y2 = pos_y1 + height
        if (mousePosX >= pos_x1 && mousePosX <= pos_x2) {
          if (mousePosY >= pos_y1 && mousePosY <= pos_y2) {
            // console.log("==================================")
            // console.log("左上点："+pos_x1 + "-" + pos_y1)
            // console.log("图片宽高："+width + "-" + height)
            // console.log("右下点："+pos_x2 + "-" + pos_y2)
            // console.log("鼠标点击点："+mousePosX+"-"+mousePosY)
            // console.log("鼠标点击坐标："+(mousePosX - pos_x1)+"-"+(mousePosY - pos_y1))

            for (let i = 0; i < this.polygonNoCheckPoint.length; i++) {
              if (this.polygonNoCheckPoint[i].fileId === this.polygonId) {
                let p = [(mousePosX - pos_x1) / width, (mousePosY - pos_y1) / height]
                this.polygonNoCheckPoint[i].point.push(p)
              }
            }
          }
        }
      })
    },
    mouseCoords(ev) {
      if (ev.pageX || ev.pageY) {
        return {x: ev.pageX, y: ev.pageY};
      }
      return {
        x: ev.clientX + document.body.scrollLeft - document.body.clientLeft,
        y: ev.clientY + document.body.scrollTop - document.body.clientTop
      };
    },

    numberAndLetter(value) {
      if (!this.reg(value)) {
        this.$message.error("任务名不符合数字或字母规范")
      }
    },

    isNumber(value) {
      if (!this.regNumber(value)) {
        this.$message.error("单车检测缓存个数,不符合数字规范")
      }
    },
    regNumber(value) {
      let reg = /^[0-9]+$/
      if (!reg.test(value)) {
        return false
      }
      return true
    },
    reg(value) {
      let reg = /^[0-9a-zA-Z]+$/
      if (!reg.test(value)) {
        return false
      }
      return true
    },
    //创建转换任务
    convertTaskButton() {
      // this.$message.error("未开放")
      this.popoverPageParams.createTaskDialogFormVisible = true
    },


    //////////////////////////////
    //listToDict
    listToDict(list) {
      let newList = []
      for (let i = 0; i < list.length; i++) {
        let xy = list[i]
        let x = xy[0]
        let y = xy[1]
        let dict = {x: x, y: y}
        newList.push(dict)
      }
      return newList
    },
    dictToList(dict) {
      let newDict = []
      for (let i = 0; i < dict.length; i++) {
        let xy = dict[i]
        let x = xy.x
        let y = xy.y
        let list = [x, y]
        newDict.push(list)
      }
      return newDict
    },

    //创建转换任务
    createConvertTask() {
      let taskLabel = this.reg(this.taskRequestData.taskName)
      if (!taskLabel) {
        let _this = this
        setTimeout(function () {
          _this.$message.error("任务名不符合数字或字母规范")
        }, 1)
      }

      let algorithmTypeLabel = (this.taskRequestData.algorithmType !== "")
      if (!algorithmTypeLabel) {
        let _this = this
        setTimeout(function () {
          _this.$message.error("算法类型不可为空")
        }, 1)
      }

      let taskTypeLabel = (this.taskRequestData.taskType !== "")
      if (!taskTypeLabel) {
        let _this = this
        setTimeout(function () {
          _this.$message.error("任务类型不可为空")
        }, 1)
      }

      let cacheNumberLabel = this.regNumber(this.taskRequestData.cacheNumber)
      if (!cacheNumberLabel) {
        let _this = this
        setTimeout(function () {
          _this.$message.error("单车检测缓存个数，不符合数字规范")
        }, 1)
      }

      let taskFilesLabel = (this.taskRequestData.taskFiles.length > 0)
      if (!taskFilesLabel) {
        let _this = this
        setTimeout(function () {
          _this.$message.error("检测文件不可为空")
        }, 1)
      }

      if (!taskLabel || !algorithmTypeLabel || !taskTypeLabel || !taskFilesLabel) {
        return
      }

      if(this.taskRequestData.algorithmType === 1 || this.taskRequestData.algorithmType === '1' || this.taskRequestData.algorithmType === 5 || this.taskRequestData.algorithmType === '5'){
        if (this.polygonPoint.length !== 0 && this.polygonPoint[0].point.length !== 0) {
          //0表示一个任务绘制一个框
          this.taskRequestData.coordPoints = this.listToDict(this.polygonPoint[0].point)
        } else {
          this.taskRequestData.coordPoints = []
        }
        if (this.polygonNoCheckPoint.length !== 0 && this.polygonNoCheckPoint[0].point.length !== 0) {
          //0表示一个任务绘制一个框
          this.taskRequestData.skipCoordPoints = this.listToDict(this.polygonNoCheckPoint[0].point)
        } else {
          this.taskRequestData.skipCoordPoints = []
        }
      } else {
        this.taskRequestData.coordPoints = []
        this.taskRequestData.skipCoordPoints = []
      }

      api({
        url: '/converttask/new',
        method: "post",
        data: this.taskRequestData
      }).then(data => {
        data = data.data
        if (data.code === '100' || data.code === 100) {
          // console.log(data.msg);
          this.taskResponseResult.msg = data.msg;
          //任务ID
          this.taskResponseResult.id = data.id;
          this.taskResponseResult.info = data.info;
          this.$message.success(this.taskResponseResult.msg)
          this.getTaskList(this.listQuery.url, this.listQuery.pageNum, this.listQuery.pageRow)
          this.popoverPageParams.createTaskDialogFormVisible = false;
        } else {
          this.$message.error(data.msg)
        }
      }).catch(data => {
        this.$message.error("创建检测任务失败")
      })
    },

    //构建文件下载链接
    getDownloadHref(fileName) {
      if (fileName === '') {
        return null
      } else {
        return this.fileDownloadUrl + "/" +fileName;
      }
    },

    //清空转换任务的所选文件ID
    clearSelectFiles() {
      this.selectNumber = 0
      this.taskRequestData.taskFiles = [];
      this.reload();
    },
    //关闭详情对话框调用
    closeDialog(dialogType) {
      if (dialogType === 1) {

        this.coordPoints = []
        this.skipCoordPoints = []
        // 去掉下拉框中选中的文件
        this.selectOption.selectTaskFileName = ''
        this.selectOption.selectResourceFileName = ''
        // 设置默认的图片
        this.resourceImageOptions.imageUrl = "./placeholder.png"
        this.taskFileImageOptions.imageUrl = "./placeholder.png"
        // 当视频框显示时，去掉视频显示
        this.resourcePlayerOptions.videoUrl = ""
        this.taskFilePlayerOptions.videoUrl = ""

        // 使图片加载出来
        this.resourceShowSwitch.show = true
        this.taskFileShowSwitch.show = true

      } else if (dialogType === 2) {

        this.dialogVisible = false
        let _this = this
        setTimeout(function () {
          _this.dialogImageUrl = ""
          _this.showSwitch.title = "图片/视频"
          _this.showSwitch.show = true
          _this.showSwitch.isCreateTask = false
          _this.showSwitch.isDrawPolygon = false
        }, 10)
      }
    },

    isImage(fileName) {
      let ext3 = fileName.substr(fileName.length - 3, 3)
      let ext4 = fileName.substr(fileName.length - 4, 4)
      let imageFlag = false;
      let errorType = false
      if (ext3 === 'jpg' || ext3 === 'png' || ext3 === 'gif' || ext3 === 'bmp' || ext3 === 'svg') {
        imageFlag = true
      } else if (ext4 === 'jpeg') {
        imageFlag = true
      } else if (ext3 === 'mp4' || ext3 === 'avi' || ext3 === 'mov' || ext3 === 'wmv' || ext3 === 'asf' || ext3 === '3gp' || ext3 === 'mkv' || ext3 === 'f4v') {
        imageFlag = false
      } else if (ext4 === 'navi' || ext4 === 'rmvb' || ext4 === 'webm') {
        imageFlag = false
      } else {
        errorType = true
      }
      return [imageFlag, errorType]
    },
    resourceChange(value, convertTaskNotifyResponse) {
      let taskFiles = convertTaskNotifyResponse.taskFiles
      let fileName = value
      let imageFlag = this.isImage(fileName)[0]
      let errorType = this.isImage(fileName)[1]

      /////////////////////////////////////
      //将非mp4的视频，改为mp4
      // let suffix = "mp4"
      // if(!imageFlag && fileName.split(".")[1] !== suffix && fileName.split(".")[1] === "avi"){
      //   fileName = fileName.split(".")[0] +"."+ suffix
      // }

      if (taskFiles[0].convertedMediaType === 'mp4') {
        fileName = fileName.split(".")[0] + "." + taskFiles[0].convertedMediaType
      }

      //离线视频
      let taskType = this.convertTaskNotifyResponse.taskType
      if (!imageFlag || taskType === '1' || taskType === 1 || taskType === 'video') {
        this.resourceShowSwitch.title = "视频浏览";
        this.resourceShowSwitch.show = false;//false是显示视频
        this.resourcePlayerOptions.videoUrl = this.resourceShowSwitch.url + "/" + fileName
      }
      //图片
      else if (imageFlag || taskType === '2' || taskType === 2 || taskType === 'image') {
        this.resourceShowSwitch.show = true;//true是显示图片
        this.resourceShowSwitch.title = "图片浏览";
        this.resourceImageOptions.imageUrl = this.resourceShowSwitch.url + "/" + fileName;
      }
      let _this = this
      setTimeout(function () {
        _this.resourceShowSwitch.dialogVisible = true
      }, 1)
    },
    taskFileChange(value, convertTaskNotifyResponse) {
      let convertedFiles = convertTaskNotifyResponse.convertedFiles
      let fileName = value
      let imageFlag = this.isImage(fileName)[0]
      let errorType = this.isImage(fileName)[1]

      /////////////////////////////////////
      //将非mp4的视频，改为mp4
      // let suffix = "mp4"
      // if(!imageFlag && fileName.split(".")[1] !== suffix && fileName.split(".")[1] === "avi"){
      //   fileName = fileName.split(".")[0] +"."+ suffix
      // }
      if (convertedFiles[0].convertedMediaType === 'mp4') {
        fileName = fileName.split(".")[0] + "." + convertedFiles[0].convertedMediaType
      }
      let taskType = this.convertTaskNotifyResponse.taskType
      this.taskFileShowSwitch.dialogVisible = true
      //离线视频
      if (!imageFlag || taskType === '1' || taskType === 1 || taskType === 'video') {
        this.taskFileShowSwitch.title = "视频浏览";
        this.taskFileShowSwitch.show = false;//false是显示视频
        this.taskFilePlayerOptions.videoUrl = this.taskFileShowSwitch.url + "/" + fileName
        if (undefined !== this.coordPoints && this.coordPoints.length > 0) {
          this.taskFileShowSwitch.isDrawPolygon = true
          this.drawImageAndPoints("targetVideoCanvas", 'targetVideoDiv', this.dictToList(this.coordPoints), [], true, false)
        } else {
          this.taskFileShowSwitch.isDrawPolygon = false
          // this.drawImageAndPoints("targetVideoCanvas", 'targetVideoDiv', [],false,false)
        }
      }
      //图片
      else if (imageFlag || taskType === '2' || taskType === 2 || taskType === 'image') {
        this.taskFileShowSwitch.show = true;//true是显示图片
        this.taskFileShowSwitch.title = "图片浏览";
        this.taskFileImageOptions.imageUrl = this.taskFileShowSwitch.url + "/" + fileName;
        if ((undefined !== this.coordPoints && this.coordPoints.length > 0) || (undefined !== this.skipCoordPoints && this.skipCoordPoints.length > 0)) {
          this.taskFileShowSwitch.isDrawPolygon = true
          if (undefined === this.coordPoints || this.coordPoints.length <= 0) {
            this.drawImageAndPoints("targetImageCanvas", 'targetImageDiv', [], this.dictToList(this.skipCoordPoints), true, false)
          } else if (undefined === this.skipCoordPoints || this.skipCoordPoints.length <= 0) {
            this.drawImageAndPoints("targetImageCanvas", 'targetImageDiv', this.dictToList(this.coordPoints), [], true, false)
          } else {
            this.drawImageAndPoints("targetImageCanvas", 'targetImageDiv', this.dictToList(this.coordPoints), this.dictToList(this.skipCoordPoints), true, false)
          }
        } else {
          this.taskFileShowSwitch.isDrawPolygon = false
          // this.drawImageAndPoints("targetImageCanvas", 'targetImageDiv', [], false, false)
        }
      }
    },

    //请求转换任务通知
    getConvertResultNotify($index) {
      //////////////////////////////////////
      //记录坐标点
      //////////////////////////////////////
      this.coordPoints = this.taskList[$index].coordPoints
      this.skipCoordPoints = this.taskList[$index].skipCoordPoints
      this.convertTaskResultNotify.id = this.taskList[$index].id;
      this.convertTaskResultNotify.taskStatus = this.taskList[$index].taskStatus;
      this.convertTaskResultNotify.convertedFiles = this.taskList[$index].convertedFiles;
      this.convertTaskResultNotify.convertedMediaType = this.taskList[$index].convertedMediaType
      // console.log(this.convertTaskResultNotify)

      this.convertTaskNotifyResponse = this.taskList[$index];
      this.pageParams.dialogFormVisible = true;
      this.taskFileShowSwitch.show = true
      this.taskFileShowSwitch.isDrawPolygon = false
    },

    //获得任务列表
    getTaskList(url, pageNum, pageRow) {
      api({
        url: url + '/?pageNum=' + pageNum + '&pageRow=' + pageRow,
        method: "get"
      }).then(data => {
        data = data.data
        if (data.code === '100' || data.code === 100) {
          // console.log(data.msg);
          this.listQuery.totalCount = data.totalCount
          this.listQuery.totalPage = data.totalPage
          this.taskList = data.list;
          this.taskList = this.algorithmSearch(this.value[0], this.value[1], this.taskList)

          this.listLoading = false;
        }
      }).catch(data => {
        this.listLoading = false;
        this.$message.error('加载任务列表失败')
      })
    },
    //获得文件列表:url=/uploadfile/list/?pageNum=5&pageRow=4"
    getFileList(url, pageNum, pageRow) {
      api({
        url: url + '/?pageNum=' + pageNum + '&pageRow=' + pageRow,
        method: "get"
      }).then(data => {
        data = data.data
        // console.log(data)
        if (data.code === '100' || data.code === 100) {
          // console.log(data.list);
          this.popoverFileList = data.list;
          this.popoverListQuery.totalCount = data.totalCount
          this.popoverListQuery.totalPage = data.totalPage
          this.popoverListLoading = false;
        } else {
          this.$message.error(data.msg)
        }
      }).catch(data => {
        this.popoverListLoading = false;
        this.$message.error('加载文件列表失败');
      })
    },
    selectFile() {
      this.popoverListLoading = true
      this.getFileList(this.popoverListQuery.url, this.popoverListQuery.pageNum, this.popoverListQuery.pageRow)
      this.popoverListLoading = false
    },
    //获得该条数据的下标索引
    getIndex($index) {
      //表格序号
      return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1
    },

    //处理页大小改变
    handleSizeChange(val) {
      // 处理当前页大小变化
      this.listQuery.pageRow = val
      // 防止数据溢出，当页大小改变时，从第一页开始查
      this.listQuery.pageNum = 1
      this.getTaskList(this.listQuery.url, 1, this.listQuery.pageRow)
    }
    ,
    //处理当前页位子改变
    handleCurrentChange(val) {
      // 处理当前页号变化
      this.listQuery.pageNum = val
      //  截取显示数据
      this.getTaskList(this.listQuery.url, this.listQuery.pageNum, this.listQuery.pageRow)
    },

    deleteConvertTask(row) {
      this.$confirm('将删除该任务, 是否确定', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let id = row.id
        let data = {id: id}
        api({
          url: "/converttask/delete",
          method: "post",
          data: data
        }).then(data => {
          data = data.data
          if (data.code === '100' || data.code === 100) {
            this.getTaskList(this.listQuery.url, this.listQuery.pageNum, this.listQuery.pageRow)
            this.$message.success(data.msg)
          }
        }).catch(data => {
          this.$message.error("删除文件失败")
        })
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    getPopoverIndex($index) {
      //表格序号
      return (this.popoverListQuery.pageNum - 1) * this.popoverListQuery.pageRow + $index + 1
    },
    //处理页大小改变
    handlePopoverSizeChange(val) {
      // 处理当前页大小变化
      this.popoverListQuery.pageRow = val
      // 防止数据溢出，当页大小改变时，从第一页开始查
      this.popoverListQuery.pageNum = 1
      this.getFileList(this.popoverListQuery.url, 1, this.popoverListQuery.pageRow)
    }
    ,
    //处理当前页位子改变
    handlePopoverCurrentChange(val) {
      // 处理当前页号变化
      this.popoverListQuery.pageNum = val
      //  截取显示数据
      this.getFileList(this.popoverListQuery.url, this.popoverListQuery.pageNum, this.popoverListQuery.pageRow)
    },
    //记录选择的文件
    handleSelectionChange(val) {
      this.taskRequestData.taskFiles = []
      this.selectNumber = val.length
      for (let i = 0; i < val.length; i++) {
        let record = val[i]
        let fileName = {fileName: record.fileName}
        let id = record.id
        let data = {fileId: id, fileName: record.fileName, convertedMediaType: record.convertedMediaType}
        this.taskRequestData.taskFiles.push(data)
      }
    },

    taskFileShow(taskFiles, fileId, fileName) {
      let fileNameTemp = fileName

      let index = 0
      for (index; index < taskFiles.length; index++) {
        if (taskFiles[index].fileId === fileId) {
          break
        }
      }

      let imageFlag = this.isImage(fileName)[0]
      let errorType = this.isImage(fileName)[1]

      ///////////////////////////
      //替换avi后缀
      if (undefined !== taskFiles[index].convertedMediaType && taskFiles[index].convertedMediaType === "mp4") {
        fileName = fileName.split(".")[0] + "." + taskFiles[index].convertedMediaType
      }

      if (!errorType) {
        if (imageFlag) {
          this.showSwitch.isCreateTask = true
          this.dialogImageUrl = this.showSwitch.url + '/' + fileName
          this.showSwitch.selectingFileName = fileNameTemp
          this.showSwitch.show = true
          this.showSwitch.title = "图片预览"
        } else {
          this.showSwitch.isCreateTask = true
          this.dialogVideoUrl = this.showSwitch.url + '/' + fileName
          this.showSwitch.selectingFileName = fileNameTemp
          this.showSwitch.show = false
          this.showSwitch.title = "视频预览"

        }
        let _this = this
        setTimeout(function () {
          _this.dialogVisible = true
        }, 100)
      } else {
        this.$message.error("文件类型错误, 不支持该格式文件")
      }
    },

    drawPolygonEvent(fileName, isCheck) {
      this.showSwitch.isDrawPolygon = true

      if (this.showSwitch.show) {
        this.showSwitch.title = "图片预览"
      } else {
        this.showSwitch.title = "视频预览"
      }

      if (isCheck) {
        this.showSwitch.title = this.showSwitch.title + "（正在绘制待检测区域）"
        document.onmousedown = this.onmouseDownCheck
      } else {
        this.showSwitch.title = this.showSwitch.title + "（正在绘制非检测区域）"
        document.onmousedown = this.onmouseDownNoCheck
      }
      let _this = this
      setTimeout(function () {
        let imageFlag = _this.isImage(fileName)[0]
        let errorType = _this.isImage(fileName)[1]

        let canvas = null
        if (_this.showSwitch.show) {
          canvas = document.getElementById('imageCanvas')
        } else {
          canvas = document.getElementById('videoCanvas')
        }
        if (canvas !== undefined && canvas != null) {

          canvas.style.opacity = '0.7'
          // 一个任务中，一个文件一个多边形
          // this.polygonId = this.taskRequestData.taskFiles[index].fileId

          //一个任务一个多边形
          _this.polygonId = 0
          let index2 = 0
          if (_this.polygonPoint.length === 0) {
            let p = {fileId: _this.polygonId, point: []}
            _this.polygonPoint.push(p)
          } else {
            for (index2; index2 < _this.polygonPoint.length; index2++) {
              if (_this.polygonPoint[index2].fileId === _this.polygonId) {
                break
              }
            }
            if (index2 === _this.polygonPoint.length) {
              let p = {fileId: _this.polygonId, point: []}
              _this.polygonPoint.push(p)
            }
          }

          let index3 = 0
          if (_this.polygonNoCheckPoint.length === 0) {
            let p = {fileId: _this.polygonId, point: []}
            _this.polygonNoCheckPoint.push(p)
          } else {
            for (index3; index3 < _this.polygonNoCheckPoint.length; index3++) {
              if (_this.polygonNoCheckPoint[index3].fileId === _this.polygonId) {
                break
              }
            }
            if (index3 === _this.polygonNoCheckPoint.length) {
              let p = {fileId: _this.polygonId, point: []}
              _this.polygonNoCheckPoint.push(p)
            }
          }
          if (!errorType) {
            if (imageFlag) {
              if (_this.showSwitch.isDrawPolygon) {
                _this.drawImageAndPoints('imageCanvas', "drawPolygonImage", _this.polygonPoint[index2].point, _this.polygonNoCheckPoint[index3].point)
              }
            } else {
              if (_this.showSwitch.isDrawPolygon) {
                _this.drawImageAndPoints('videoCanvas', "drawPolygonVideo", _this.polygonPoint[index2].point, _this.polygonNoCheckPoint[index3].point)
              }
            }
          } else {
            _this.$message.error("文件类型错误, 不支持该格式文件")
          }
        }
      }, 10)

    },

    drawImageAndPoints(canvasId, imageOrVideoId, pointsOne, pointsTwo, flag = true, ifPointer = true, colorOne = 'red', colorTwo = 'green') {    //  获取canvas

      this.$nextTick(() => {
        let canvas = document.getElementById(canvasId)    //由于弹窗，确保已获取到
        let imageOrVideo = document.getElementById(imageOrVideoId)
        // console.log(imageOrVideo)

        let _this = this
        setTimeout(function () {
          if (undefined !== canvas && canvas != null) {
            let a = setInterval(() => {
              canvas = document.getElementById(canvasId)
              let div = document.getElementsByClassName('collapseDiv')

              for (let i = 0; i < div.length; i++) {
                div[i].style.width = imageOrVideo.clientWidth + "px"
                div[i].style.height = imageOrVideo.clientHeight + "px"
              }
              _this.dialogStyle.width = imageOrVideo.clientWidth
              _this.dialogStyle.height = imageOrVideo.clientHeight
              if (!canvas) {
                return false
              } else {
                clearInterval(a)            //  可以理解为一个画笔，可画路径、矩形、文字、图像
                let context = canvas.getContext('2d')
                //  根据图像重新设定了canvas的长宽
                canvas.setAttribute("width", _this.dialogStyle.width.toString())
                canvas.setAttribute("height", _this.dialogStyle.height.toString())           //  绘制图片

                // console.log("=================================")
                // console.log("imageOrVideo的大小："+_this.dialogStyle.width +"---"+ _this.dialogStyle.height)
                // console.log("imageOrVideo2的大小："+imageOrVideo.clientWidth +"---"+ imageOrVideo.clientHeight)

                // console.log(img.width+"-"+img.height)
                if (flag && pointsOne != null && pointsOne.length > 0) {
                  context.beginPath()
                  for (let i = 0; i < pointsOne.length; i++) {
                    let point1 = pointsOne[i]
                    let x1 = point1[0] * _this.dialogStyle.width
                    let y1 = point1[1] * _this.dialogStyle.height
                    let x2 = 0
                    let y2 = 0
                    if (i < pointsOne.length - 1) {
                      let point2 = pointsOne[i + 1]
                      x2 = point2[0] * _this.dialogStyle.width
                      y2 = point2[1] * _this.dialogStyle.height
                    } else {
                      let point2 = pointsOne[0]
                      x2 = point2[0] * _this.dialogStyle.width
                      y2 = point2[1] * _this.dialogStyle.height
                    }
                    context.moveTo(x1, y1)
                    context.lineTo(x2, y2)
                    context.strokeStyle = colorOne
                    context.lineWidth = 3;
                    context.stroke()
                  }
                }

                if (flag && pointsTwo != null && pointsTwo.length > 0) {
                  context.beginPath()
                  for (let i = 0; i < pointsTwo.length; i++) {
                    let point1 = pointsTwo[i]
                    let x1 = point1[0] * _this.dialogStyle.width
                    let y1 = point1[1] * _this.dialogStyle.height
                    let x2 = 0
                    let y2 = 0
                    if (i < pointsTwo.length - 1) {
                      let point2 = pointsTwo[i + 1]
                      x2 = point2[0] * _this.dialogStyle.width
                      y2 = point2[1] * _this.dialogStyle.height
                    } else {
                      let point2 = pointsTwo[0]
                      x2 = point2[0] * _this.dialogStyle.width
                      y2 = point2[1] * _this.dialogStyle.height
                    }
                    context.moveTo(x1, y1)
                    context.lineTo(x2, y2)
                    context.strokeStyle = colorTwo
                    context.lineWidth = 3;
                    context.stroke()
                  }
                }
                if (ifPointer) {
                  canvas.style.pointerEvents = "auto"
                } else {
                  canvas.style.pointerEvents = "none"
                }
              }
            }, 50)
          }
        }, 130)
      })
    },

  }
}
</script>


<style rel="stylesheet/scss" lang="scss">
@import url("//unpkg.com/element-ui@2.14.1/lib/theme-chalk/index.css");

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 6px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 100%;
}

.clearfix::after {
  content: "";
  display: block;
  clear: both;
}

</style>
